package com.warrior.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.warrior.configer.ConfigHelper;
import com.warrior.entity.HomeIntroductionEntity;
import com.warrior.entity.IntroductionContentEntity;
import com.warrior.service.HomeIntroductionService;
import com.warrior.service.UtilsTools;
import com.warrior.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 后台首页介绍controller
 * Created by shawn on 2017/4/24.
 */
@Controller
@RequestMapping("/admin")
public class AdminIntroductionController {


    @Autowired
    private HomeIntroductionService homeIntroductionService;

    @Autowired
    private UtilsTools utilsTools;
    /**
     * 添加首页
     * @param request request
     * @param response response
     * @return ModelAndView
     */
    @RequestMapping("/homeIntroduction")
    public ModelAndView homeIntroductionPage(HttpServletRequest request, HttpServletResponse response , String homeIntroductionId){
        ModelAndView mv = new CModelAndView("admin/index_config_edit",request,response);
        if(null!=homeIntroductionId){
            HomeIntroductionEntity homeIntroductionEntity = this.homeIntroductionService.findHomeIntroductionById(homeIntroductionId);
            mv.addObject("homeIntroductionEntity",homeIntroductionEntity);
        }
        return mv;
    }

    /**
     * 添加首页介绍标题
     * @param id  首页介绍文章主键id(修改时传入,添加置空)
     * @param name 记录活动介绍 的名称
     * @param shortTitle 记录首页介绍短标
     * @param sequence 记录首页介绍序列
     * @param request request
     * @return String
     */
    @RequestMapping("/add_introduction")
    @ResponseBody
    public String addIntroduction(String id,String name,String shortTitle,String sequence,HttpServletRequest request){
        HomeIntroductionEntity homeIntroductionEntity = new HomeIntroductionEntity();
        DateUtil dateUtil = new DateUtil();
        if (null!=id && !"".equals( id)){
            homeIntroductionEntity = this.homeIntroductionService.findHomeIntroductionById(id);
        }else {
            homeIntroductionEntity.setId("HA-"+ UUID.randomUUID().toString().replace("-",""));
            homeIntroductionEntity.setCreatedAt(dateUtil.Date2Timestamp(new Date()));
        }
        homeIntroductionEntity.setCreatedBy("admin");
        homeIntroductionEntity.setUpdateBy("admin");

        homeIntroductionEntity.setUpdateAt(dateUtil.Date2Timestamp(new Date()));

        homeIntroductionEntity.setName(name);
        homeIntroductionEntity.setShortTitle(shortTitle);
        homeIntroductionEntity.setSequence(CommonUtils.String2Int(sequence));
        // 图片上传开始
        String uploadFilePath = ConfigHelper.getConfig().getString("upload.path");
        String saveFilePathName = request.getSession().getServletContext()
                .getRealPath("/") + uploadFilePath + "/User_photo";
        Map map;
        String fileName = "";
        try {
            map = UploadUtils.saveFileToServer(request, "photo", saveFilePathName,
                    fileName, null);
            if (fileName.equals("")) {
                if (map.get("fileName") != "") {
                    fileName = (String) map.get("fileName");
                    String savePath = "/upload/User_photo/" + fileName;
                    homeIntroductionEntity.setPicPath(savePath);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        this.homeIntroductionService.saveHomeIntroduction(homeIntroductionEntity);
        String returnMap = null;
        try {
            returnMap= ServerResponse.okToJsonString("success");
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return returnMap;
    }


    /**
     * 根据首页介绍id获取首页介绍内容的list
     * @param request req
     * @param response resp
     * @param homeId 首页介绍id
     * @return ModelAndView
     */
    @RequestMapping(value = "/introduction/contents_list")
    public ModelAndView introductionContentList(HttpServletRequest request,HttpServletResponse response,String homeId){
        ModelAndView mv = new CModelAndView("admin/index_detail_edit",request,response);
        List<IntroductionContentEntity> contentEntities = this.homeIntroductionService.findContentByHomeId(homeId);
        mv.addObject("contentEntities",contentEntities);
        mv.addObject("homeId",homeId);
        mv.addObject("utilsTools",utilsTools);
        return mv;
    }

    /**
     * 编辑修改展示的内容
     * @param contentId 内容id
     * @param text 内容文本(如果有)
     * @param picPath 图片路径(如果有)
     * @param videoPath 视频地址(如果有)
     * @param sequence 序列
     * @return json
     */
    @RequestMapping(value = "/introduction/contents_edit")
    @ResponseBody
    public String introductionContentEdit(String contentId,String text,String picPath,String videoPath,String sequence,HttpServletRequest request,String introductionId){
        IntroductionContentEntity contentEntity;
        DateUtil dateUtil = new DateUtil();
        //如果有id则为添加,如果没有则为修改
        if (null!= contentId && !"".equals(contentId)){
            contentEntity = this.homeIntroductionService.findContentById(contentId);
        }else {
            contentEntity = new IntroductionContentEntity();
            contentEntity.setId("II-"+UUID.randomUUID().toString().replace("-",""));
            contentEntity.setCreatedAt(dateUtil.Date2Timestamp(new Date()));
            contentEntity.setCreatedBy("admin");
        }
        contentEntity.setIntroductionText(text);
        if(picPath!=null){
            // 图片上传开始
            String uploadFilePath = ConfigHelper.getConfig().getString("upload.path");
            String saveFilePathName = request.getSession().getServletContext()
                    .getRealPath("/") + uploadFilePath + "/User_photo";
            Map map;
            String fileName = "";
            try {
                map = UploadUtils.saveFileToServer(request, "photo", saveFilePathName,
                        fileName, null);
                if (fileName.equals("")) {
                    if (map.get("fileName") != "") {
                        fileName = (String) map.get("fileName");
                        String savePath = "/upload/User_photo/" + fileName;
                        contentEntity.setIntroductionPicPath(savePath);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        contentEntity.setIntroductionVideoPath(videoPath);
        contentEntity.setIntroductionSequence(CommonUtils.String2Int(sequence));
        contentEntity.setUpdateAt(dateUtil.Date2Timestamp(new Date()));
        contentEntity.setUpdateBy("admin");
        contentEntity.setIntroductionId(introductionId);
        this.homeIntroductionService.saveIntroductionContent(contentEntity);
        String returnMap = null;
        try {
            returnMap= ServerResponse.okToJsonString("success");
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return returnMap;
    }

    /**
     * 删除首页介绍内容
     * @param contentId 内容id
     * @return json
     */
    @RequestMapping(value = "/introduction/content_delete",method = RequestMethod.DELETE)
    @ResponseBody
    public String introductionContentDelete(String contentId){
        this.homeIntroductionService.deleteHomeIntroductionContent(contentId);
        String returnMap = null;
        try {
            returnMap= ServerResponse.okToJsonString("success");
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return returnMap;
    }

    /**
     *删除首页介绍
     * @param introductionId 首页介绍id
     * @return json
     */
    @RequestMapping(value = "/introduction/introduction_delete",method = RequestMethod.DELETE)
    @ResponseBody
    public String introductionDelete(String introductionId){
        this.homeIntroductionService.deleteHomeIntroduction(introductionId);
        String returnMap = null;
        try {
            returnMap= ServerResponse.okToJsonString("success");
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return returnMap;
    }


    /**
     * 首页介绍list
     * @param request req
     * @param response resp
     * @param size 页面大小
     * @param page 当前页
     * @return ModelAndView
     */
    @RequestMapping(value = "/introduction/introduction_list")
    public ModelAndView introductionList(HttpServletRequest request,HttpServletResponse response,String size,String page){
        if (null==page || "".equals(page)){
            page = "0";
        }
        ModelAndView mv = new CModelAndView("admin/index_config_list",request,response);
        Page<HomeIntroductionEntity> listAllHomeIntroduction = this.homeIntroductionService.listAllHomeIntroduction(CommonUtils.String2Int(size), CommonUtils.String2Int(page));
        mv.addObject("introductions",listAllHomeIntroduction);

        return mv;
     }


}
